#include <iostream>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <string.h>
#include <sys/wait.h>

int main()
{
    // 创建管道
    int pipefd[2] = {0};
    if (pipe(pipefd) < 0)
    {
        std::cout << "pipe error" << std::endl;
        return -1;
    }
    // 创建子进程
    pid_t pid = fork();
    if (pid < 0)
    {
        std::cout << "fork error" << std::endl;
        return -1;
    }

    else if (pid == 0)  
    {  
        // 子进程  
        // 关闭写端  
        ::close(pipefd[1]);  
        dup2(pipefd[0], 0);  
        ::close(pipefd[0]); // 关闭不再需要的管道读端  

        // 正确的实现方法：直接从pipefd[0]读取  
        int ret;  
        while (1)  
        {  
            int fd = ::read(0, &ret, sizeof(ret)); // 从pipefd[0]读取  
            if (fd < 0)  
            {  
                std::cout << "read error" << std::endl;  
                exit(1);  
            }  
            else if (fd == 0)  
            {  
                std::cout << "pipe closed" << std::endl;  
                break; // 退出循环  
            }  
            std::cout << "i am father cnt : " << ret << std::endl;  
            sleep(1);  
        }  
        exit(0); // 正常退出子进程  
    }
    else
    {
        // 父进程
        // 关闭读端
        ::close(pipefd[0]);
        int cnt = 10;
        while (cnt)
        {

            ::write(pipefd[1], &cnt, sizeof(cnt));
            cnt--;
            sleep(1);
        }
        ::close(pipefd[1]);
        int wait = ::waitpid(pid, NULL, 0);
        if (wait < 0)
        {
            std::cout << "waitpid error" << std::endl;
            return -1;
        }
    }

    return 0;
}